package logic

import (
	"context"
	"errors"
	"math/rand"
	"regexp"
	"time"
	"video-hub/models/cache"
	"video-hub/videorpc/internal/svc"
	"video-hub/videorpc/videorpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type SendSmsLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewSendSmsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *SendSmsLogic {
	return &SendSmsLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 发送验证码
func (l *SendSmsLogic) SendSms(in *videorpc.SendSmsRequest) (*videorpc.SendSmsResponse, error) {
	// todo: add your logic here and delete this line

	matchString, err := regexp.MatchString(`^1[3-9]\d{9}$`, in.Phone)
	if err != nil {
		return nil, err
	}
	if !matchString {
		return nil, errors.New("该手机号格式不正确,应为11位数字")
	}

	i, _ := cache.Rdb.Get(l.ctx, "smsNum_"+in.Phone).Int64()
	if i >= 1 {
		return nil, errors.New("1分钟内同一手机号仅能1分钟内仅允许发送1次验证码")
	}

	code := rand.Intn(9000) + 1000
	//sms, err := pkg.SendSms(in.Phone, strconv.Itoa(code))
	//if err != nil {
	//	return nil, err
	//}
	//if sms.Code != 2 {
	//	return nil, errors.New(sms.Msg)
	//}
	cache.Rdb.Set(l.ctx, "smsCode_"+in.Phone, code, time.Minute*5)

	incr, _ := cache.Rdb.Incr(l.ctx, "smsNum_"+in.Phone).Result()
	if incr == 1 {
		cache.Rdb.Expire(l.ctx, "smsNum_"+in.Phone, time.Minute*1)
	}

	return &videorpc.SendSmsResponse{}, nil
}
